﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace DFGK_WMS.WebAPI.Filter    
{
    public class LogActionFilter : ActionFilterAttribute
    {
        private readonly ILogger<LogActionFilter> logger;
        private readonly ITInterfaceLogRepository tInterfaceLog;

        public LogActionFilter(ILogger<LogActionFilter> logger, ITInterfaceLogRepository tInterfaceLog)
        {
            this.logger = logger;
            this.tInterfaceLog = tInterfaceLog;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //var guid = Guid.NewGuid().ToString();
            //context.HttpContext.Request.Headers.Add("X-Request-ID", guid);

            base.OnActionExecuting(context);
        }


        public override void OnResultExecuted(ResultExecutedContext context)
        {
            base.OnResultExecuted(context);
            Console.WriteLine("请求后"+context);

            var url = context.HttpContext.Request.Path; // 获取请求的URL
    
            // 获取控制器和操作方法的参数值
            var controller = context.RouteData.Values["controller"]?.ToString();
            var action = context.RouteData.Values["action"]?.ToString();

            if (context.Result is ObjectResult objectResult)
            {
                var resultData = JsonConvert.SerializeObject(objectResult.Value); // 获取响应的数据
                Console.WriteLine("响应数据：" + resultData);
        
                // 在这里使用url、controller、action和resultData进行日志记录或其他操作
                // ...
            }

            //tInterfaceLog.Add(new TInterfaceLog()
            //{
            //     CallWayStr = context.HttpContext.Request.Method.ToString(),
            //     Url=context.HttpContext.Request.Path,
            //     CreateDate = DateTime.Now,
            //     InParam= JsonConvert.SerializeObject(context.ActionArguments?.Values),
            //});
        }
    }
}
